package com.rocksea.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.rocksea.app.activity.InpseFromActivity;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.entry.InspectionForm;
import com.rocksea.app.fragment.FileCenterFragment;
import com.rocksea.app.http.CommHttpTask;
import com.rocksea.app.http.HttpUtil;
import com.rocksea.app.http.OnRespond;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * @author by Mrw_v @date on 2018/9/27
 */

public class PlanListActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    public static final String INTENT_KEY = "INTENT_KEY";
    public static final String CHOOSE_INDEX = "CHOOSE_INDEX";
    public static final String MODE_KEY = "MODE_KEY";
    public static final String SECT_KEY = "SECT_KEY";
    public static final String SITE_KEY = "SITE_KEY";

    public static int InspectionType = 1;
    public static final String KEY = "From_Type";

    @InjectView(R.id.planList) ListView mPlanList;
    @InjectView(R.id.SwipeRefreshLayout) SwipeRefreshLayout mSwipeRefreshLayout;
    private ArrayList<InspectionForm.InspectionFormListBean> inspectionForms;
    private int planId;
    private int mSiteId;
    private int mSectId;
    private PlanAdapter mPlanAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plan_list_activity_layout);
        ButterKnife.inject(this);
        ActionBar mActionBar = getSupportActionBar();
        if (mActionBar!=null)
        {
            mActionBar.setTitle("报检单列表");
            mActionBar.setHomeButtonEnabled(true);
            mActionBar.setDisplayHomeAsUpEnabled(true);
        }
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mPlanList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
            {
                boolean enable = false;
                if (view != null && view.getChildCount() > 0) {
                    boolean firstItemVisible = view.getFirstVisiblePosition() == 0;
                    boolean topOfFirstItemVisible = view.getChildAt(0).getTop() == 0;
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                mSwipeRefreshLayout.setEnabled(enable);
            }});
        initData(getIntent());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    protected void initData(Intent intent)
    {
        inspectionForms = intent.getParcelableArrayListExtra(INTENT_KEY);
        planId = intent.getIntExtra(PlanListActivity.CHOOSE_INDEX,0);
        Collections.reverse(inspectionForms);
        InspectionType = intent.getIntExtra(MODE_KEY,1);
        mSectId = intent.getIntExtra(SECT_KEY,0);
        mSiteId = intent.getIntExtra(SITE_KEY,0);
        mPlanAdapter = new PlanAdapter();
        mPlanList.setAdapter(mPlanAdapter);
        mPlanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                ChoosePlanEvent choosePlanEvent = new ChoosePlanEvent();
                choosePlanEvent.formListBean = inspectionForms.get(i);
                EventBus.getDefault().post(choosePlanEvent);
                finish();
            }
        });
    }

    @Override
    public void onRefresh()
    {
        if (InspectionType == 1)
        {
            requestBridgeFormService();
        }
        else
        {
            requestRodeFormService();
        }
    }

    private class PlanAdapter extends BaseAdapter
    {
        @Override
        public int getCount()
        {
            return inspectionForms.size();
        }

        @Override
        public Object getItem(int i)
        {
            return null;
        }

        @Override
        public long getItemId(int i)
        {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup)
        {
            if (view == null)
                view = View.inflate(getBaseContext(),R.layout.plan_item,null);
            TextView planNum = (TextView) view.findViewById(R.id.planNum);
            TextView time = (TextView) view.findViewById(R.id.time);
            TextView method = (TextView) view.findViewById(R.id.method);
            View planItem = view.findViewById(R.id.planItem);
            if (inspectionForms.get(i).id == planId)
            {
                planItem.setBackground(ContextCompat.getDrawable(getBaseContext(),R.drawable.uploaded_background));
            }
            else
            {
                planItem.setBackground(ContextCompat.getDrawable(getBaseContext(),R.drawable.item_selecter_layout));
            }
            switch (inspectionForms.get(i).applyMethod)
            {
                case "1":
                    method.setText("低应变");
                    break;

                case "2":
                    method.setText("高应变");
                    break;

                case "3":
                    method.setText("声测");
                    break;

                case "4":
                    method.setText("静载");
                    break;
            }
            TextView operation = (TextView) view.findViewById(R.id.operation);
            operation.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // finish current activity and post event to FileCenterFragment fresh TextView planTv
                    InspectionForm.InspectionFormListBean formListBean = inspectionForms.get(i);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(UiUtils.BUNDLE_KEY,formListBean);
                    bundle.putString("PileNum",formListBean.number);
                    bundle.putInt(KEY,InspectionType);
                    UiUtils.JumpActivity(PlanListActivity.this, InpseFromActivity.class,bundle);

                }
            });
            planNum.setText(inspectionForms.get(i).number);
            time.setText(inspectionForms.get(i).applyTime);
            return view;
        }
    }

    public static class ChoosePlanEvent
    {
        public ArrayList<InspectionForm.InspectionFormListBean> mInspectionFormListBeans;
        public InspectionForm.InspectionFormListBean formListBean;
        public ChoosePlanEvent(){}
    }


    private void requestRodeFormService()
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0", Account.getRandomCode());
        mRequest.put("in1",String.valueOf(mSectId));
        mRequest.put("in2",String.valueOf(mSiteId));
        mRequest.put("in3", PerUtils.dateToStr(new Date(new Date().getTime()- DbCenter.DAY_OF_TIME*30*12)));
        mRequest.put("in4",PerUtils.dateToStr(new Date()));
        HttpUtil.http(CommHttpTask.DOWN_INSPECTION_FROM_1,mRequest,new DownLoadPlanRespond(mSectId,mSiteId));
    }

    private void requestBridgeFormService()
    {
        LinkedHashMap<String,Object> mRequest = new LinkedHashMap<>();
        mRequest.put("in0", Account.getRandomCode());
        mRequest.put("in1",String.valueOf(mSectId));
        mRequest.put("in2",String.valueOf(mSiteId));
        mRequest.put("in3",PerUtils.dateToStr(new Date(new Date().getTime()-DbCenter.DAY_OF_TIME*30*12)));
        mRequest.put("in4",PerUtils.dateToStr(new Date()));
        HttpUtil.http(CommHttpTask.DOWN_INSPECTION_FROM,mRequest,new DownLoadPlanRespond(mSectId,mSiteId));
    }

    private class DownLoadPlanRespond implements OnRespond
    {
        private long sectId;
        private long siteId;

        DownLoadPlanRespond(long sectId,long siteId)
        {
            this.sectId = sectId;
            this.siteId = siteId;
        }

        @Override
        public void onSucceed(String json)
        {
            mSwipeRefreshLayout.setRefreshing(false);
            try
            {
                InspectionForm mInspectionForm = JSON.parseObject(json, InspectionForm.class);
                if (!mInspectionForm.flag.equals("0"))
                {
                    UiUtils.showToast("更新报检单失败,请重新登陆后再试");
                    return;
                }
            }
            catch (Exception e)
            {
                UiUtils.showToast("更新报检单失败,请重新登陆后再试");
            }
            handlerPlanData(json,sectId,siteId);
        }
        @Override
        public void onError(int code, String error)
        {
            UiUtils.showToast("网络异常,请检测网络");
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void handlerPlanData(String json,long sectId,long siteId)
    {
        mSwipeRefreshLayout.setRefreshing(false);
        try
        {
            InspectionForm mInspectionForm = JSON.parseObject(json, InspectionForm.class);
            if (mInspectionForm.flag.equals("0"))
            {
                PerUtils.setString(String.format("%s$%s$%s",FileCenterFragment.PLAN_KEY,sectId,siteId),json);
                if (mInspectionForm.inspectionFormList == null || mInspectionForm.inspectionFormList.size() == 0)
                {
                    UiUtils.showToast("暂无报检单");
                    inspectionForms.clear();
                    return;
                }
                DbCenter.savePileId(mInspectionForm.inspectionFormList);
                inspectionForms.clear();
                for (InspectionForm.InspectionFormListBean inspectionFormListBean : mInspectionForm.inspectionFormList)
                {
                    inspectionForms.add(0,inspectionFormListBean);
                }
                UiUtils.showToast("更新报检单完成");
                ChoosePlanEvent choosePlanEvent = new ChoosePlanEvent();
                choosePlanEvent.mInspectionFormListBeans = (ArrayList<InspectionForm.InspectionFormListBean>) mInspectionForm.inspectionFormList;
                EventBus.getDefault().post(choosePlanEvent);
                mPlanAdapter.notifyDataSetChanged();
            }
        }
        catch (Exception e)
        {
            UiUtils.showToast("更新失败(请检查是否账户被他人占用)");
        }

    }
}
